'''
Created on Aug 26, 2010

@author: dexen
'''
import os 
import sys
import random
import time

#INITIALISATION 
#function for generating genotype
def random_genotype(size):
    genotype = []
    for _ in range(size):
        random.seed()
        genotype.append(random.random())
    return genotype

#DEVELOPMENT
def enableHouModule():
    '''Set up the environment so that "import hou" works.'''
    # Importing hou will load in Houdini's libraries and initialize Houdini.
    # In turn, Houdini will load any HDK extensions written in C++.  These
    # extensions need to link against Houdini's libraries, so we need to
    # make sure that the symbols from Houdini's libraries are visible to
    # other libraries that Houdini loads.  So, we adjust Python's dlopen
    # flags before importing hou.
    if hasattr(sys, "setdlopenflags"):
        old_dlopen_flags = sys.getdlopenflags()
        import DLFCN
        sys.setdlopenflags(old_dlopen_flags | DLFCN.RTLD_GLOBAL)

    try:
        import hou
    except ImportError:
        # Add $HFS/houdini/python2.5libs to sys.path so Python can find the
        # hou module.
        sys.path.append( os.environ['HFS'] + "/houdini/python%d.%dlibs" % sys.version_info[:2])
        import hou
    finally:
        if hasattr(sys, "setdlopenflags"):
            sys.setdlopenflags(old_dlopen_flags)
            
#houdini geometry
def houdini(genotypes, basefilepath, filename, count):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    hou.hipFile.load(basefile)
    genotype = hou.node("/obj/geo1/genotypes")
    for cnt in range(len(genotypes)):
        genotype.setParms({"genotype"+str(cnt+1):genotypes[cnt]})
        
    phenotype_geom = os.path.join(basefilepath, "phenotype")
    if not os.path.isdir(phenotype_geom):
        os.mkdir(phenotype_geom)

    hou.node("/obj/geo1/phenotype").geometry().saveToFile(phenotype_geom + "/houseschema.bgeo")
    
def sim_ep(basefilepath, filename):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    hou.hipFile.load(basefile)
    hou.node("/obj/geo1/OUT").cook()
    node = hou.node("/obj/geo1/OUT")
    prim = node.geometry().prims()[0]
    att = prim.attribValue("TotalEnergyTransfer [KWh]")
    return att 

def sim_rad(basefilepath, filename):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    hou.hipFile.load(basefile)
    hou.node("/obj/geo1/OUT").cook()
    node = hou.node("/obj/geo1/OUT")
    pts = node.geometry().points()
    illum_list = []
    for pt in pts:
        illum = pt.attribValue("illuminance")
        if illum > 300 :
            illum_list.append(illum)
    total_pts = len(pts)
    illum_pts = len(illum_list)
    percentage = float(illum_pts)/float(total_pts)*100
    return percentage

def sim_privacy(basefilepath, filename):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    hou.hipFile.load(basefile)
    hou.node("/obj/geo1/OUT").cook()
    node = hou.node("/obj/geo1/OUT")
    prims = node.geometry().prims()
    privacy_list = []
    for prim in prims:
        p = prim.attribValue("privacy_score")
        privacy_list.append(p)
    
    total = sum(privacy_list)
    return total

def sim_display(basefilepath, filename):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    display_result_geom = os.path.join(basefilepath, "display_result_geom")
    if not os.path.isdir(display_result_geom):
        os.mkdir(display_result_geom)
        
    hou.hipFile.load(basefile)
    hou.node("/obj/geo1/OUT").cook()
    hou.node("/obj/geo1/OUT").geometry().saveToFile(display_result_geom + "/houseschema.bgeo")
    

def site_generation(genotypes, basefilepath, filename, count):
    enableHouModule()
    import hou
    basefile = os.path.join(basefilepath, filename)
    hou.hipFile.load(basefile)
    genotype = hou.node("/obj/geo1/genotypes")
    for cnt in range(len(genotypes)):
        genotype.setParms({"genotype"+str(cnt+1):genotypes[cnt]})
        
    site_geom = os.path.join(basefilepath, "site_geom", "privacy")
    if not os.path.isdir(site_geom):
        os.mkdir(site_geom)
    
    site_geom1 = os.path.join(basefilepath, "site_geom", "eprad")
    if not os.path.isdir(site_geom1):
        os.mkdir(site_geom1)
            
    hou.node("/obj/geo1/site_geom").geometry().saveToFile(site_geom + "/site" + count + ".bgeo")
    hou.node("/obj/geo1/site_geom_eprad").geometry().saveToFile(site_geom1 + "/eprad" + count + ".bgeo")
    
def write_results(results,basefilepath):
    result_filepath = os.path.join(basefilepath, "overallresult")
    if not os.path.isdir(result_filepath):
        os.mkdir(result_filepath)
    prevdir = os.getcwd()
    os.chdir(result_filepath)
    result_file = open("finalresult.csv",  "w")
    #write the results into a csv file 
    result_file.write("project_id,daylight(% points less than 300lux),total_energy_transfer(kWh)(daily_avg),privacy_score\n")
    result_file.write(results)
    result_file.close()
    os.chdir(prevdir)
#site generation 
'''
num_iter = 5

for count in range(num_iter):
    #development
    genotypes = random_genotype(56)
    print count
    print genotypes
    basefilepath = "/home/dexen/workspace/house_schema/houdinibasefile"
    filename = "houseschema.hipnc"
    count = str(count)
    site_generation(genotypes, basefilepath, filename, count)
'''

def main():
    #developmental script     
    num_iter = 1
    energy_list = []
    daylight_list = []
    privacy_list = []
    results = ""
    for count in range(num_iter):
        #development
        genotypes = [0.92656492558681514, 0.50761973211257905, 0.82555427584547292, 0.98663468184406256, 0.79729138113309261, 0.81107068601237109, 0.76947961195068082, 0.17241588028340815, 0.13448895371803882, 0.51440916673519199, 0.57294707847793036, 0.10169731220396538, 0.42969035312529547, 0.11127285990138125, 0.7966303315891371, 0.57863579277384203, 0.31302701236949759, 0.3267981759915205, 0.27971101181346825, 0.31624275967655613, 0.47983765917785226, 0.17238914229074787, 0.36227533216907826, 0.8986716318128869, 0.8911276872944901, 0.94784978237013606, 0.18157451424467586, 0.98467232499498214, 0.38945659722084991, 0.67708268865868315, 0.72160775207968542, 0.64025745306777371, 0.86636412770962767, 0.30654042468052667, 0.21497321112476853, 0.36187851077140498, 0.24010623016027821, 0.79847471369625234, 0.25721551640768103, 0.66621480347383655, 0.37418411273496011, 0.47969040982208144, 0.87926674398142335, 0.34433264778931183, 0.66278102888383394, 0.31560531758005039, 0.90783311703422176, 0.92112729538658289, 0.17856186434123289, 0.27836511337517944, 0.10491990746670898, 0.86125685641446026, 0.83218039671056521, 0.47150683471739108, 0.80000214802015635, 0.0052978282592944792]
        print count
        print genotypes
        basefilepath = os.path.join(os.getcwd(), "houdinibasefile")
        filename = "houseschema.hipnc"
        count = str(count)
        houdini(genotypes, basefilepath, filename, count)
        
        s_basefilepath = basefilepath
        #output the display geometry
        
        s_time = time.time()
        s_filename = "display_geom.hipnc"
        sim_display(s_basefilepath, s_filename)
        print "Running time:", time.time() - s_time

        #evaluation
        s_time = time.time()
        s_filename = "sim_ep.hipnc"
        energy = sim_ep(s_basefilepath, s_filename)
        print "Running time:", time.time() - s_time
        
        s_time = time.time()
        s_filename = "sim_rad.hipnc"
        daylight = sim_rad(s_basefilepath, s_filename)
        print "Running time:", time.time() - s_time

        s_time = time.time()
        s_filename = "sim_privacy.hipnc"
        privacy = sim_privacy(s_basefilepath, s_filename)
        print "Running time:", time.time() - s_time
        
        results = results + str(count) + ","+ str(daylight) + "," +  str(energy) + "," +\
          str(privacy) +"\n" 
          
    
    #write the results into a csv file 
    basefilepath = "/home/kafkef/workspace/house_schema"
    write_results(results,basefilepath)
    

if __name__ == "__main__":
    main()
